<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>自定义查询添加编辑</title>
    <link rel="stylesheet" href="${ctx}/css/form.css">
    <#include "/pubHeadStyleTree.html">
    <script src="${ctx}/formStatic/verify.js"></script>
    <script src="${ctx}/formStatic/form/form.js"></script>
</head>
<body>
<div style="position: relative;height: 100%" id="treePre">
    <div class="ccpui-trees">
        <p class="isShowTree colorSwitch">
                <span style="float: left;color: white">&nbsp;&nbsp;树结构管理</span>
            <i layadmin-event="treeFlexible" class="layui-icon layui-icon-prev"></i>
        </p>
            <div style="margin-top: 6px;">
                <ul class="ccpui-iconTree iconTrees">
                    <li><a class="iconfont iconshuaxin- zTree-refresh" title="刷新"></a></li>
                    <li><a class="iconfont iconwenjianjia1-copy zTree-triangle-d" title="展开"></a></li>
                    <li><a class="iconfont iconfolder1 zTree-triangle-r" title="收起"></a></li>
                    <input type="text" style="width: 50%" class="tablePreviewValue">
                </ul>
                <ul id="treeStructureClass" class="ztree ccpui-listZtree"></ul>
            </div>
    </div>
    <div class="ccpui-coreContent" style="padding-left:7px;">
        <p class="colorSwitch" style="cursor: pointer;height: 30px;line-height: 30px;">
            <span style="color: white;">
            &nbsp;&nbsp;编辑
            </span>
        </p>
        <div class="formPreview" style="width: 100%;margin: 10px auto auto;">
            <form class="layui-form" lay-filter="formData" id="formDefEdit">
                <div>
                    <button class="layui-btn layui-btn-sm save" lay-submit lay-filter="dataTemplateForm">保存</button>
                </div>
                <div class="templateDetail templateAddEdit" style="overflow: hidden;padding: 5px 20px;">
                </div>
                <input type="hidden" name="formData" id="formData"/>
                <input type="hidden" id="id" name="id" />
                <input type='hidden' id='tableId' name='tableId'/>
                <input type='hidden' id='alias' name='alias'/>
            </form>
        </div>
    </div>
</div>
<!--zTree树右键菜单-->
<div class="formDefRightMenus">
    <div id="nodeRightMenus">
        <ul>
            <li id="addNode">新增</li>
            <li id="editNode">编辑</li>
            <li id="removeNode">删除</li>
        </ul>
    </div>

</div>
<div class="formDefRightMenus">
    <div id="nullRightMenus">
        <ul>
            <li id="addNodePlace">新增</li>
        </ul>
    </div>
</div>

<script>
    var formKey = '${formKey}';
    //在获取表单数据时会用到，getData()中
    var needVer = '${needVer}';
    var tableName = '${tableName}';
    $(".save").hide();
    var jsPreScript = '';
    var jsAfterScript = '';
    var zTree;
    layui.config({
        base: serverPath.formPath + staticPath.formPath //静态资源所在路径
    }).extend({
        index: 'index' //主入口模块
    }).use(['index','setter', 'ice', 'form', 'element', 'layer', 'slider', 'colorpicker', 'form', 'table', 'totalFilter', 'propsHandle', 'commons'], function () {

        // -----常量声明----------
        var $ = layui.$,
            setter = layui.setter,  // 配置信息
            layer = layui.layer,
            ice = layui.ice,
            propsHandle = layui.propsHandle,
            form = layui.form,
            commons = layui.commons,
            defProps = {
                viewMould: 'form/formDef/view/formDesign/moulds/', // 组件模块 存放文件 *****
                initCss: [
                    'style/forms/grid/grid1',
                    'style/forms/grid/grid2',
                    'style/forms/grid/grid3',
                    'style/forms/template/tag',
                    'style/forms/template/text',
                    'style/forms/template/table',
                    'style/forms/template/textArea',
                    'style/forms/template/radioOption',
                    'style/forms/template/date',
                    'style/forms/template/button',
                    'style/forms/template/uploadFile',
                    'style/forms/template/richText',
                    'style/forms/template/select',
                    'style/forms/template/checkOption',
                    'style/forms/template/dataLexi',
                    'style/forms/template/uploadImg',
                    'style/forms/template/selector',
                    'style/forms/formDevise',
                    'style/forms/dragLay',
                    'style/forms/formPreview'
                ],
                formAreaInfo: 'html',
                temDate: '.temDate',
                uploadFileBtn: '.uploadFileBtn',
                uploadImgBtn: '.uploadImgBtn',
                richTextArea: '.richTextArea',
                selectInput: '.selectInput',
                radioOptionCont: '.radioOptionCont',
                dataLexiTree: '.dataLexiTree',
                selectorBtn: '.selectorBtn'
            },
            temQuery = new propsHandle()  // 实例化模板功能部分
        ;
        // init 模板部分渲染
        ice.loadCss(defProps.initCss);

        var treeStructureData;
        //获取树结构数据
        $.ajax({
            url: serverPath.formPath + setter.formLinkPath +"formDefTree/getObject",
            type: "GET",
            contentType: 'application/json',
            dataType: 'json',
            data: {"action": "formDefTree", "formKey": formKey},
            success: function (result) {
                if(commons._filterRecord(result)){
                    treeStructureData = result.data;
                }
            }
        });

        //刷新
        $(".zTree-refresh").click(function () {
            preZtrees();
        });
        //展开
        $(".zTree-triangle-d").click(function () {
            $.fn.zTree.getZTreeObj("treeStructureClass").expandAll(true);
        });
        //收起
        $(".zTree-triangle-r").click(function () {
            $.fn.zTree.getZTreeObj("treeStructureClass").expandAll(false);
        });
        preZtrees();
        //左侧ztree树
        function preZtrees() {
            var setting={
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "parentId"
                    },
                    key: {
                        name: "name"
                    }
                },
                async:{
                    enable:true,
                    url:serverPath.formPath + setter.formLinkPath +"formDefTree/getObject",
                    autoParam:["id"],
                    otherParam:{"action":"json","formKey": formKey},
                    dataType:'json',
                    dataFilter:filter
                },
                view: {
                    showLine: false,
                    nameIsHTML: true, //允许name支持html
                    selectedMulti: false
                },
                edit: {
                    enable: false,
                    editNameSelectAll: false
                },
                callback: {
                    onClick:onClickType,
                    onRightClick:OnRightClickres
                }
            };
            //处理返回数据
            function filter(treeId,parentNode,responseData){
                return responseData.data;
            }
            zTree = $.fn.zTree.init($('#treeStructureClass'), setting);
            component.fuzzySearch('treeStructureClass', '.tablePreviewValue', null, true); //初始化模糊搜索方法
        }
        //节点点击事件
        // var treeId = "";
        function onClickType(event, treeId, treeNode) {
            //节点详细
            $.ajax({
                url: serverPath.formPath + setter.formLinkPath +'dataTemplate/detailData?alias=' + formKey,
                dataType: 'json',
                data:{"id":treeNode.dataId},
                success: function (result) {
                    if (commons._filterRecord(result)) {
                        $(".save").hide();
                        $(".templateDetail").html(result.data.form);
                        dataParse(result,treeNode.dataId);
                    } else {
                        window.parent.layer.alert(result.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert("预览失败！" + XMLHttpRequest.status);
                }
            });
        }
        //右键菜单
        function OnRightClickres(event, treeId, treeNode) {
            if (treeNode && !treeNode.noR) {
                ztreeNode = treeNode;
                // selectResId = treeNode.typeId;
                parentIds = treeNode.parentId;
                showRMenus(event.clientX, event.clientY);
            }else {
                showNullRMenus(event.clientX, event.clientY);
            }
        }

        function showRMenus(x, y) {
            $("#nodeRightMenus ul").show();
            var nodeRightMenus = $('#nodeRightMenus');
            var h = nodeRightMenus.height();
            x += 15;
            y += 10;
            if ($(window).height() < y + h) (
                y = y - h
            );
            nodeRightMenus.css({"top": y + "px", "left": x + "px", "visibility": "visible"});

            $("body").bind("mousedown", onBodyMouseDown);
        }
        function onBodyMouseDown(event) {
            if (!(event.target.id == "orgRightMenu" || $(event.target).parents("#nodeRightMenus").length > 0 || $(event.target).parents("#classRightMenus").length > 0)) {
                $("#nodeRightMenus").css({"visibility": "hidden"});
            }
            if (!(event.target.id == "orgRightMenu" || $(event.target).parents("#nullRightMenus").length > 0 || $(event.target).parents("#classRightMenus").length > 0)) {
                $("#nullRightMenus").css({"visibility": "hidden"});
            }
        }
        function showNullRMenus(x, y) {
            $("#nullRightMenus ul").show();
            var nullRightMenus = $('#nullRightMenus');
            var h = nullRightMenus.height();
            x += 15;
            y += 10;
            if ($(window).height() < y + h) (
                y = y - h
            );
            nullRightMenus.css({"top": y + "px", "left": x + "px", "visibility": "visible"});
            $("body").bind("mousedown", onBodyMouseDown);
        }
        //右键菜单点击事件
        $("#reFlash").click(function () {
            preZtrees();
            $("#nodeRightMenus").css({"visibility": "hidden"});
        });

        //子节点添加
        $("#addNode").click(function () {
            $.ajax({
                url: serverPath.formPath + setter.formLinkPath +'dataTemplate/editData?alias=' + formKey,
                dataType: 'json',
                data:{"fId":ztreeNode.dataId},
                success: function (result) {
                    if (commons._filterRecord(result)) {
                        $(".save").show();
                        $(".templateAddEdit").html(result.data.formDef.html);
                        $("#tableId").val(result.data.tableId);
                        $("#alias").val(result.data.alias);
                        var sysBusEvent = result.data.sysBusEvent;
                        if (sysBusEvent != null) {
                            jsPreScript = sysBusEvent.jsPreScript;
                            jsAfterScript = sysBusEvent.jsAfterScript;
                        }
                        $("#id").val();
                        dataParse(result,null);
                        $("input[name='m:"+tableName+":"+treeStructureData.parentId+"']").val(ztreeNode.id);
                        form.render();
                    } else {
                        window.parent.layer.alert(result.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert("添加失败！" + XMLHttpRequest.status);
                }
            });

        });

        //编辑节点
        $("#editNode").click(function () {
            $.ajax({
                url: serverPath.formPath + setter.formLinkPath +'dataTemplate/editData?alias=' + formKey,
                dataType: 'json',
                data:{"id":ztreeNode.dataId},
                success: function (result) {
                    if (commons._filterRecord(result)) {
                        $(".save").show();
                        $(".templateAddEdit").html(result.data.formDef.html);
                        $("#tableId").val(result.data.tableId);
                        $("#alias").val(result.data.alias);
                        var sysBusEvent = result.data.sysBusEvent;
                        if (sysBusEvent != null) {
                            jsPreScript = sysBusEvent.jsPreScript;
                            jsAfterScript = sysBusEvent.jsAfterScript;
                        }
                        $("#id").val(result.data.id);
                        dataParse(result,ztreeNode.dataId);
                    } else {
                        window.parent.layer.alert(result.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert("编辑失败！" + XMLHttpRequest.status);
                }
            });
        });
        //删除节点
        $("#removeNode").click(function () {
            var nodeArray=zTree.transformToArray(ztreeNode);
            var ids = ztreeNode.dataId;
            for(var i = 1;i < nodeArray.length;i++){
                ids = ids + "," + nodeArray[i].dataId;
            }
            layer.confirm('确定删除当前节点吗？', function (index) {
                $.ajax({
                    url: serverPath.formPath + setter.formLinkPath +'dataTemplate/batchDeleteData?alias='+formKey,
                    type: "post",
                    dataType:'json',
                    data: {"ids": ids},
                    success: function (result) {
                        if (commons._filterRecord(result)) {
                            layer.alert(result.msg);
                        } else {
                            preZtrees();
                            $(".templateDetail").html("");
                            $(".save").hide();
                            layer.alert(result.msg);
                        }
                    }
                });
                layer.close(index);
            });
        });

        //根节点添加
        $("#addNodePlace").click(function () {
            $.ajax({
                url: serverPath.formPath + setter.formLinkPath +'dataTemplate/editData?alias=' + formKey,
                dataType: 'json',
                data:{"fId":"0"},
                success: function (result) {
                    if (commons._filterRecord(result)) {
                        $(".save").show();
                        $(".templateAddEdit").html(result.data.formDef.html);
                        $("#tableId").val(result.data.tableId);
                        $("#alias").val(result.data.alias);
                        var sysBusEvent = result.data.sysBusEvent;
                        if (sysBusEvent != null) {
                            jsPreScript = sysBusEvent.jsPreScript;
                            jsAfterScript = sysBusEvent.jsAfterScript;
                        }

                        $("#id").val("");
                        dataParse(result,null);
                        if(treeStructureData.rootPId == null){
                            $("input[name='m:"+tableName+":"+treeStructureData.parentId+"']").val("0");
                        }else{
                            $("input[name='m:"+tableName+":"+treeStructureData.parentId+"']").val(treeStructureData.rootPId);
                        }
                        form.render();
                    } else {
                        window.parent.layer.alert(result.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert("编辑失败！" + XMLHttpRequest.status);
                }
            });
        });
        //数据加载的解析
        function dataParse(result,id) {
                var mainData = result.data.mainFields;
                var subData = result.data.subFields;
                permission = result.data.permission;
                var sysBusEvent = result.data.sysBusEvent;
                if (sysBusEvent != null) {
                    jsPreScript = sysBusEvent.jsPreScript;
                    jsAfterScript = sysBusEvent.jsAfterScript;
                }
                //回显时候需要在选择器的input上加上ids的值
                $(".selectorInfo").each(function () {
                    var inputObj = $(this).children();
                    if ($(this).children().attr("name") != undefined) {
                        var name = $(this).children().attr("name").split(":");
                        var selectorId = name[2] + "id";
                        inputObj.val(mainData[name[2].toLocaleLowerCase()]);
                        inputObj.attr("ids", mainData[selectorId.toLocaleLowerCase()]);
                    }
                });
                if (id) {
                    //回显下拉选项的值
                    $(".temSelectCont").each(function () {
                        var value = $(this).attr("val");
                        $(this).val(value);
                    });
                    //回显radio 单选按钮的值
                    $(".radioOptionCont").each(function () {
                        var name = $(this).attr("name").split(":");
                        var fieldName = name[2];
                        $(this).find('input:radio').each(function () {
                                if ($(this).val() == mainData[fieldName.toLocaleLowerCase()]) {
                                    $(this).prop('checked', true);
                                }
                            }
                        )
                    });
                    //回显复选的值
                    $(".checkOptionCont").each(function () {
                        var name = $(this).attr("name").split(":");
                        var fieldName = name[2];
                        $(this).find('input:checkbox').each(function () {
                            var fieldVal = mainData[fieldName.toLocaleLowerCase()];
                            if (fieldVal != null && fieldVal.indexOf($(this).val()) > -1) {
                                $(this).prop("checked", true);
                            }
                        })
                    });

                    //回显数据字典的值
                    $("input.dataLexiVal").each(function () {
                        var name = $(this).attr("name").split(":");
                        var fieldName = name[2];
                        $(this).prev().text(mainData[fieldName.toLocaleLowerCase()]);
                    });

                    //回显文件上传
                    $(".uploadFileList").each(function () {
                        var name = $(this).attr('name');
                        var fieldName = name.replace(/.*:/, '');
                        var flag = getUploadFileIsMain(subData, $(this));
                        if (flag) {
                            if (mainData[fieldName.toLocaleLowerCase()] != "" && mainData[fieldName.toLocaleLowerCase()] != undefined) {
                                var fileIdArray = JSON.parse(mainData[fieldName.toLocaleLowerCase()]);
                                if (fileIdArray.length > 0) {
                                    for (var i = 0; i < fileIdArray.length; i++) {
                                        var str = '<li fileId=' + fileIdArray[i]["fileid"] + '><p>' + fileIdArray[i]["name"] + '</p><i class="layui-icon layui-icon-delete deleteFile" ></i></li>';
                                        //只读权限
                                        if (permission['field'][fieldName] == "r") {
                                            str = '<li fileId=' + fileIdArray[i]["fileid"] + '><p>' + fileIdArray[i]["name"] + '</p></li>';
                                        }
                                        $(this).append(str);
                                    }
                                }
                            }
                        }
                    });

                    //回显图片上传
                    $(".uploadImgList").each(function () {
                        var name = $(this).attr('name');
                        var fieldName = name.replace(/.*:/, '');
                        var flag = getUploadFileIsMain(subData, $(this));
                        if (flag) {
                            if (mainData[fieldName.toLocaleLowerCase()] != "" && mainData[fieldName.toLocaleLowerCase()] != undefined) {
                                var fileIdArray = JSON.parse(mainData[fieldName.toLocaleLowerCase()]);
                                if (fileIdArray.length > 0) {
                                    for (var i = 0; i < fileIdArray.length; i++) {
                                        var str = '<li fileId=' + fileIdArray[i] + '><div class="fileByImg"><img src="' + serverPath.formPath + setter.sysLinkPath + 'attachFile/getFileById?fileId=' + fileIdArray[i] + '" /></div><i class="layui-icon layui-icon-delete deleteFile" ></li>'
                                        //只读权限
                                        if (permission['field'][fieldName] == "r") {
                                            str = '<li fileId=' + fileIdArray[i] + '><div class="fileByImg"><img src="' + serverPath.formPath + setter.sysLinkPath + 'attachFile/getFileById?fileId=' + fileIdArray[i] + '" /></div></li>'
                                        }
                                        $(this).append(str);
                                    }
                                }
                            }
                        }
                    });
                    form.render();
                }
                if (subData) {
                    processSubData(subData);
                }
                temQuery.initTemEvent(defProps, serverPath, setter)
                form.render();
        }

        //自定义验证规则 验证数据字典、单选复选、图片、文件必填
        form.verify({
            required: function (value, item) {
                var tr = $(item).parents("tr");
                if(tr.hasClass("subContTem")){
                }else{
                    var fieldValue = $(item).val();
                    if (fieldValue == "") {
                        return '必填项不能为空';
                    }
                }
            },
            dic: function (value, item) {
                var fieldName = $(item).attr('name').split(":")[2];
                if (permission['field'][fieldName] == "b") {//数据字典必填
                    var fieldValue = $(item).val();
                    if (fieldValue == "0") {
                        $(item).parent().css({"border": "1px solid #FF5722"});
                        return '必填项不能为空';
                    }else{
                        $(item).parent().css({"border": ""});
                    }
                }
            },
            checkRadio: function (value, item) {
                //单选框 复选框
                var radioName = $(item).parent().parent().attr('name').split(":");
                //var radioName = $(".tableExcel .radioOptionCont").attr("name").split(":");
                var radioFieldName = radioName[2];
                if (permission['field'][radioFieldName] == "b") {//单选框必填
                    var verifyElem = $(item).parent().parent().find('input');
                    var isTrue = false;
                    for (var k = 0; k < verifyElem.length; k++) {
                        isTrue = $(verifyElem[k]).is(':checked');//是否命中校验
                        if (isTrue) {
                            break;
                        }
                    }
                    if (!isTrue) {
                        $(item).parent().parent().css({"border": "1px solid #FF5722"});
                        return '必填项不能为空';
                    }else{
                        $(item).parent().parent().css({"border": ""});
                    }
                }
            },
            imageAndFile: function (value, item) {
                var fieldName = $(item).attr('name').split(":")[2];
                if (permission['field'][fieldName] == "b") {//图片文件必填
                    var children = $(item).children();
                    if (children.length == 0) {
                        $(item).parent().css({"border": "1px solid #FF5722"});
                        return '必填项不能为空';
                    }else{
                        $(item).parent().css({"border": ""});
                    }
                }
            },
            subDic: function (value, item) {

                var tr = $(item).parents("tr");
                if(tr.hasClass("subContTem")){
                }else{
                    var fieldName = $(item).attr('name').split(":")[2];
                    if (permission['table'][fieldName] == "b") {//数据字典必填
                        var fieldValue = $(item).val();
                        if (fieldValue == "0") {
                            $(item).parent().css({"border": "1px solid #FF5722"});
                            return '必填项不能为空';
                        }else{
                            $(item).parent().css({"border": ""});
                        }
                    }
                }

            },
            subCheckRadio: function (value, item) {

                var tr = $(item).parents("tr");
                if(tr.hasClass("subContTem")){
                }else{
                    //单选框 复选框
                    var radioName = $(item).parent().parent().attr("name").split(":");
                    var radioFieldName = radioName[2];
                    if (permission['table'][radioFieldName] == "b") {//单选框必填
                        var verifyElem = $(item).parent().parent().find('input');
                        var isTrue = false;
                        for (var k = 0; k < verifyElem.length; k++) {
                            isTrue = $(verifyElem[k]).is(':checked');//是否命中校验
                            if (isTrue) {
                                break;
                            }
                        }
                        if (!isTrue) {
                            $(item).parent().parent().css({"border": "1px solid #FF5722"});
                            return '必填项不能为空';
                        }else{
                            $(item).parent().parent().css({"border": ""});
                        }
                    }
                }

            },
            subImageAndFile: function (value, item) {
                var tr = $(item).parents("tr");
                if(tr.hasClass("subContTem")){
                }else{
                    var fieldName = $(item).attr('name').split(":")[2];
                    if (permission['table'][fieldName] == "b") {//图片文件必填
                        var children = $(item).children();
                        if (children.length == 0) {
                            $(item).parent().css({"border": "1px solid #FF5722"});
                            return '必填项不能为空';
                        }else{
                            $(item).parent().css({"border": ""});
                        }
                    }
                }

            }
        });

        // 初始化模板功能
        temQuery.initTem({
            selectorBtn: defProps.selectorBtn,
            selectorTemPath: setter.views + defProps.viewMould
        });

        // 保存表单数据
        form.on('submit(dataTemplateForm)', function (data) {
            // 执行 js 前置代码
            if (jsPreScript != null && jsPreScript !== '') {
                var jsPreReturn = new Function(jsPreScript)();
                if (!jsPreReturn) {
                    return false;
                }
            }
            data.field.formData = getData();
            $.ajax({
                url: serverPath.formPath + setter.formLinkPath + "formHandler/add",
                type: "POST",
                dataType: 'json',
                data: data.field,
                success: function (result) {
                    if (commons._filterRecord(result)) {
                        layer.msg("保存成功！");
                        // 执行 js 后置代码
                        if (jsAfterScript != null  && jsAfterScript !== '') {
                            new Function(jsAfterScript)();
                        }
                        window.location.reload();
                    } else {
                        window.parent.layer.alert(result.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert("保存失败！" + XMLHttpRequest.status);
                }
            });
            return false;
        });

        //判断附件和图片是否是主表里面的元素
        function getUploadFileIsMain(subData, obj) {
            var flag = true;
            for (var p = 0; p < subData.length; p++) {
                var subTableName = subData[p].tableName;
                var tableClass = "temTable " + subTableName + " subFormTable";
                if ($(obj).parents("table ." + tableClass).length > 0) {
                    flag = false;
                }
            }
            return flag;
        }

        //子表数据回显
        function processSubData(subData) {
            for (var h = 0; h < subData.length; h++) {
                var subTableName = subData[h].tableName;
                var dataList = subData[h].dataList;
                for (var k = 0; k < dataList.length; k++) {
                    if (k > 0) {
                        var cloneTr = $("." + subTableName + " tr.temSpace");
                        var trLength = cloneTr.length;
                        $(cloneTr[trLength - 1]).clone().appendTo("." + subTableName);
                        var cloneTr = $("." + subTableName + " tr.temSpace");
                        //新增的序号赋值
                        var index = cloneTr.length-2;
                        $(cloneTr[cloneTr.length-1]).find("div.temTag").text(index);
                        //radio的input name赋值name="zdxan_2"
                        var radioDiv = $(cloneTr[cloneTr.length-1]).find("div.radioOptionCont");
                        radioDiv.find('input:radio').each(function () {
                            var attrName = $(this).attr("name");
                            var indexStr = "_"+(index-1).toString();
                            var newIndexStr = "_"+index.toString();
                            if(attrName.indexOf(indexStr) > -1){
                                attrName= attrName.replace(indexStr,newIndexStr);
                            }else{
                                attrName= attrName+newIndexStr;
                            }
                            $(this).attr("name",attrName);
                        })
                    }
                }
            }
            for (var i = 0; i < subData.length; i++) {
                var subTableName = subData[i].tableName;
                var dataList = subData[i].dataList;
                var inputName = "s:" + subTableName;
                for (var j = 0; j < dataList.length; j++) {
                    var trObjs = $("." + subTableName + " tr.temSpace");
                    var jsonObj = dataList[j];
                    for (var key in jsonObj) {
                        var attrName = inputName + ":" + key;
                        var inputObj = $(trObjs[j + 2]).children().find("input[name='" + attrName + "']");
                        var selectObj = $(trObjs[j + 2]).children().find("select[name='" + attrName + "']");
                        var divObj = $(trObjs[j + 2]).children().find("div[name='" + attrName + "']");
                        var ulObj = $(trObjs[j + 2]).children().find("ul[name='" + attrName + "']");
                        var objVal = jsonObj[key];
                        if (selectObj.length > 0) {
                            $(selectObj).val(objVal);
                        }
                        if (inputObj.length > 0) {
                            $(inputObj).val(objVal);
                            //选择器input上赋上属性ids
                            if (inputObj.hasClass("selectorInput")) {
                                var selectorId = key + "id";
                                inputObj.attr("ids", jsonObj[selectorId]);
                            }
                            if (inputObj.hasClass("dataLexiVal")) {
                                inputObj.prev().text(objVal);
                            }
                        }
                        //附件 图片
                        if (ulObj.length > 0) {
                            var fileIdArray = JSON.parse(objVal);
                            for (var g = 0; g < fileIdArray.length; g++) {
                                var str = '<li fileId=' + fileIdArray[g]["fileid"] + '><p>' + fileIdArray[g]["name"] + '</p><i class="layui-icon layui-icon-delete deleteFile" ></i></li>';
                                if (ulObj.hasClass("uploadImgList")) {
                                    str = '<li fileId=' + fileIdArray[g] + '><div class="fileByImg"><img src="' + serverPath.formPath + setter.sysLinkPath + 'attachFile/getFileById?fileId=' + fileIdArray[g] + '" /></div><i class="layui-icon layui-icon-delete deleteFile" ></li>'
                                }
                                if (permission['table'][key] == "r") {
                                    str = '<li fileId=' + fileIdArray[g]["fileid"] + '><p>' + fileIdArray[g]["name"] + '</p></li>';
                                    if (ulObj.hasClass("uploadImgList")) {
                                        str = '<li fileId=' + fileIdArray[g] + '><div class="fileByImg"><img src="' + serverPath.formPath + setter.sysLinkPath + 'attachFile/getFileById?fileId=' + fileIdArray[g] + '" /></div></li>'
                                    }
                                }
                                ulObj.append(str);
                            }
                        }
                        if (divObj.length > 0) {
                            divObj.find('input:checkbox').each(function () {
                                if (objVal != null && objVal.indexOf($(this).val()) > -1) {
                                    $(this).prop("checked", true);
                                }
                            });
                            //处理单选按钮
                            divObj.find('input:radio').each(function () {
                                if ($(this).val() === objVal) {
                                    $(this).prop('checked', true);
                                }
                            })
                        }
                        var textareaObj = $(trObjs[j + 2]).children().find("textarea[name='" + attrName + "']");
                        $(textareaObj).val(objVal);
                    }
                }
            }
            form.render();
        }
        // 子表初始化事件
        temQuery.initSubEvent(defProps, serverPath, setter);

        //加载规则验证数据
        $.ajax({
            url: serverPath.formPath + setter.formLinkPath + 'formRule/getRuleByFormKey',
            dataType: 'json',
            data: {"formKey": formKey},
            success: function (result) {
                if (commons._filterRecord(result)) {
                    var ruleString = "layui.use('form',function(){"+
                        "var form = layui.form;"+
                        "form.render();"+
                        "form.verify({";
                    if(result.data!==null){
                        for(var i=0;i<result.data.length;i++){
                            var ruleData = result.data[i];
                            ruleString += ruleData.alias+":function (value, item) {" +
                                "        if (!(/" + ruleData.rule + "/.test(value))) {" +
                                "            return '" + ruleData.tipInfo + "';" +
                                "        }" +
                                "    },";
                        }
                    }
                    ruleString += "}); });";
                    // 执行 js 代码
                    if(result.data!==null) {
                        if (result.data.length > 0) {
                            var ruleJs = new Function(ruleString)();
                            if (!ruleJs) {
                                return false;
                            }
                        }
                    }
                }else {
                    window.parent.layer.alert(result.msg);
                }
            }
        });
    });
</script>
<style>
    #nodeRightMenus,#nullRightMenus{
        position: fixed;
        border: 1px solid #ccc;
        z-index: 900;
        visibility: hidden;
        top: 0;
        background-color: #f5f5f5;
        text-align: left;
        padding: 2px;
    }
    #nodeRightMenus>ul>li,#nullRightMenus>ul>li{
        color: #666666;
        margin: 5px 0;
        padding: 0 8px;
        cursor: pointer;
        list-style: none outside none;
    }
</style>
</body>
</html>